import { createApp } from "vue";

import Cookies from "js-cookie";
// import locale from "element-plus/lib/locale/lang/zh-cn"; // 中文语言
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import "tailwindcss/tailwind.css";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import "xe-utils";
import VXETable from "vxe-table";
import "vxe-table/lib/style.css";
import DKVui from "dk-vui";
import "dk-vui/dist/style.css";
import "@/assets/styles/index.scss"; // global css
import App from "./App";
import store from "./store";
import router from "./router";
import directive from "./directive/index.js";
import { getPeriod, getBank } from './api/index.js'
import 'dayjs/locale/zh-cn'

// 全局组件
import SelectPersonnel from "@/components/SelectPersonnel";
import multiInput from '@/components/multiInput';
import dataAuthority from '@/components/dataAuthority';
// import Public from '@/componentsPublic'

// svg图标
import "virtual:svg-icons-register";
import SvgIcon from "@/components/SvgIcon";

import {
  renderWithQiankun,
  qiankunWindow,
} from "vite-plugin-qiankun/dist/helper";
import { name as packageName } from "../package.json";
import { resetForm, openLink } from "@/utils/index.js";
import { copy } from "@/utils/index.js";
import { defaultTime } from "@/utils/config.js";

import pinia from '@/store/index';
import keepAliveStore from "@/store/modules/keepalive";
const keepeStore = keepAliveStore(pinia)
import action from '@/utils/action.js';
import { routes, history } from '@/router/index'
import { initMatomo } from '@/utils/initMatomo'
// 甘特图
import dhtmlxGantt from '@/plugins/dhtmlxGantt';
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'
import echarts from '@/utils/echarts'

import useCommonStore from "@/store/modules/common";
const commonStore = useCommonStore();
// import { navigateToNewRoute } from './App.vue'
import { conditionSave, queryConditionList, conditionDelete } from '@/api/index.js'
import { useRouter } from "vue-router"

let app;
function render(props) {
  app = createApp(App);
  initMatomo(app)
  commonStore.getAttributesList()
  const {
    container,
    $parentRouter,
    routerEvent,
  } = props;

  // 主应用全局数据
  app.config.globalProperties.$onGlobalStateChange = props.onGlobalStateChange;
  app.config.globalProperties.$setGlobalState = props.setGlobalState;
  app.config.globalProperties.$echarts = echarts
  // 公共方法
  app.config.globalProperties.resetForm = resetForm;
  app.config.globalProperties.copy = copy;
  app.config.globalProperties.dataAuthority = dataAuthority;
  
  // 公共配置
  app.config.globalProperties.defaultTime = defaultTime;
  app.config.globalProperties.openLink = openLink;

  app.use(DKVui, { scrollHideForm: true })
  DKVui.setup({
    keepStore: keepAliveStore,
    useRouter,
    table: {
      scrollHideForm: true,
      formConfig: {
        proxy: {
          mainKey: 'id', // 主键
          query: ({ model_type }) => queryConditionList({ apiName: model_type }),
          // model_type 类型/ name 保存名称 / sc_id 主键 / conditions保存条件
          save: ({ model_type, name, id, conditions }) => conditionSave({ apiName: model_type, name, id, condition: conditions }),
          remove: ({ model_type, name, id }) => conditionDelete({ apiName: model_type, name, id })
        }
      }
    },
    select: {
      types: {
        period: getPeriod, // 结算方式
        bank: getBank, // 银行列表
      }
    }
  })
  app.use(router);
  app.use(store);
  app.use(VXETable);
  // VXETable.use(VXETablePluginElement)
  
  app.use(SelectPersonnel);
  app.use(dhtmlxGantt);
  app.component("select-personnel", SelectPersonnel);
  app.component("multi-input", multiInput);
  app.component("svg-icon", SvgIcon);
  app.component("dataAuthority", dataAuthority);
  directive(app);
  // 使用element-plus 并且设置全局的大小
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
  }
  app.use(ElementPlus, {
    locale: zhCn,
    size: Cookies.get("size") || "default",
  });

  const c = container
    ? container.querySelector("#app")
    : document.getElementById("app");


  // router = createRouter({
  //   history: createMemoryHistory(window.__POWERED_BY_QIANKUN__ ? '' : `/goods/task/develop`),
  //   routes
  // })

  // router.beforeEach((to, _form, next) => {
  //   if (_form.path !== '/') {
  //     if (to.path === '/empty') {
  //       next()
  //       return
  //     }
  //     let {
  //       parentName,
  //       childrenName
  //     } = to.meta

  //     if ((parentName && parentName === _form.name) || (childrenName && childrenName.some((item) => item === _form.name)) || (parentName && _form.meta.parentName && parentName === _form.meta.parentName)) {
  //       keepeStore.closeKeepaliveList(_form)
  //       keepeStore.pushKeepaliveList(to['name'])


  //       action.setGlobalState({
  //         changeMicoTabsPath: {
  //           to: to,
  //           appName: 'goods',
  //           type: "change"
  //         }
  //       })
  //     }
  //   }

  //   next()
  // })

  if (routerEvent) {
    // 如果首次跳转子页面就直接跳到父级页面
    let path = routes.find(item => item.path === routerEvent.path)
    // 页面路由跳转加上?mustJump=true  可以强制跳转子页面  暂未使用 后续自由扩展
    if ((path && path.mate && path.meta.parentName) && !(routerEvent && routerEvent.query && routerEvent.query.mustJump)) {
      let parent = routes.find(item => item.name === path['meta']['parentName'])
      $parentRouter.push(parent.path)
      keepeStore.pushKeepaliveList(parent.name)
      action.setGlobalState({
        changeMicoTabsPath: {
          to: {
            path: parent.path,
            fullPath: parent.path,
            query: {},
          },
          appName: 'app1',
          type: "change"
        }
      })
      return
    } else {
      const newPath = routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, '/');
      // const newFullPath = routerEvent.fullPath && routerEvent.fullPath.replace(/\/[^/]*\//, '/');
      // router.push(newFullPath)
      let find = routes.find(item => item.path === newPath)
      find && keepeStore.pushKeepaliveList(find.name)
    }

    requestAnimationFrame(() => {
      action.setGlobalState({
        changeMicoTabsPath: {
          type: "changeLoading",
          loading: false
        }
      })
    })
  }
  app.mount(c);
}

const base = window.__POWERED_BY_QIANKUN__ ? '/goods' : ''
// router.afterEach((to, from, next) => {
//   // const state = {
//   //   ...history.state,
//   //   current: base + to.fullPath
//   //   // current: to.path.indexOf(base) === -1 ? removeDuplicateString(base + to.fullPath) : to.fullPath
//   // }
//   // history.replaceState(state, '', window.location.href)
//
//   if (!history.state.current) {
//     history.state.current = window.location.pathname;
//   }
// })

renderWithQiankun({
  mount(props) {
    action.setActions(props)
    render(props);
  },
  bootstrap() { },
  unmount(props) {
    app.unmount();
    app._container.innerHTML = '';
    app = null
    // router = null
    // history.destroy()
  },
  update(props) {
    let {
      routerEvent
    } = props
    if (routerEvent) {
      console.log("routerEvent")
      console.log(routerEvent)

      switch (routerEvent.type) {
        case 'push': {
          console.log('执行添加')
          const newPath = routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, '/');
          // const newFullPath = routerEvent.fullPath && routerEvent.fullPath.replace(/\/[^/]*\//, '/');
          // router.push(newFullPath)
          const path = routes.find(item => item.path === newPath)
          keepeStore.pushKeepaliveList(path?.name)
        }
          break
        case 'replace': {
          console.log('执行替换')
          // const newPath = routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, '/');
          // const newFullPath = routerEvent.fullPath && routerEvent.fullPath.replace(/\/[^/]*\//, '/');
          // keepeStore.closeKeepaliveList(routes.find(item => item.path === newPath))
          // this.navigateToNewRoute(newFullPath)
          // router.replace(newFullPath)
          // nexctTick(()=>{

          // })
        }
          break
        case 'close': {
          const newPath = routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, '/');
          keepeStore.closeKeepaliveList(routes.find(item => item.path === newPath))
        }
          break
        case 'refresh': {
          const newPath = routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, '/');
          keepeStore.closeKeepaliveList(routes.find(item => item.path === newPath))
        }
          break
        case 'visible': {
          // router.push('/empty')
          console.warn('执行visible')
        }
          break
      }
    }
  },
});

// 独立运行时
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render({});
}